'use strict';

const uidObj = require('uni-id');
const {
	Controller
} = require('uni-cloud-router');
const dbcmd = uniCloud.database().command;
const $ = dbcmd.aggregate;

module.exports = class CouponController extends Controller {
	
	// 领券
	async receive() {
		let response = {
			code: 1,
		};
		
		const start = new Date().getTime();
		const {
			rule_id
		} = this.ctx.data;
		
		let uid = '';
		let user = {
			openid: '',
			name: '',
			headimg: '',
			mobile: ''
		};
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
				if (userRes.userInfo.wx_openid) {
					user.openid = userRes.userInfo.wx_openid['mp-weixin'];
				}
				user.name = userRes.userInfo.nickname || userRes.userInfo.username;
				user.headimg = userRes.userInfo.avatar;
				user.mobile = userRes.userInfo.mobile || '';
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		
		// 获取优惠券规则
		const couponRuleRes = await this.db.collection('usemall-marketing-coupon-rule').doc(rule_id).get();
		let couponRule = {};
		if (couponRuleRes.data && couponRuleRes.data.length === 1) {
			couponRule = couponRuleRes.data[0];
		}
		
		if (!(couponRule && couponRule._id) || couponRule.is_delete == 1) {
			response.msg = `优惠券【${rule_id}】不存在`;
			return response;
		}
		if (couponRule.state != '运营中')
		{
			response.msg = `优惠券状态【${couponRule.state}】`;
			return response;
		}
		if (couponRule.receive_type != '主动发放')
		{
			response.msg = `优惠券领取规则为【${obj.receive_type}】`;
			return response;
		}
		if (couponRule.end_time < Date.now())
		{
			response.msg =`优惠券已过期`;
			return response;
		}
		
		// todo 判断用户是否已领取、是否可领
		
		
		// 获取可待领取的一张优惠券
		const couponRes = await this.db.collection('usemall-marketing-coupon')
			.where({
				is_delete: 0,
				state: '待领取',
				coupon_id: rule_id
			})
			.orderBy('sort', 'desc')
			.limit(1)
			.get();
		
		let coupon = {};
		if (couponRes.data && couponRes.data.length === 1) {
			coupon = couponRes.data[0];
		}
		if (!(coupon && coupon._id)) {
			response.msg = `优惠券已领完`;
			return response;
		}
		
		await this.__receive_coupon(uid, user, rule_id, coupon._id, `【${user.name}】领取优惠券`);
		
		response.datas = '成功领取1张优惠券';
		
		const end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}
	
	// 兑换
	async exchange() {
		let response = {
			code: 1,
		};
		
		const start = new Date().getTime();
		const {
			code
		} = this.ctx.data;
		
		let uid = '';
		let user = {
			openid: '',
			name: '',
			headimg: '',
			mobile: ''
		};
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
				if (userRes.userInfo.wx_openid) {
					user.openid = userRes.userInfo.wx_openid['mp-weixin'];
				}
				user.name = userRes.userInfo.nickname || userRes.userInfo.username;
				user.headimg = userRes.userInfo.avatar;
				user.mobile = userRes.userInfo.mobile || '';
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		
		// 根据兑换码获取优惠券
		const couponRes = await this.db.collection('usemall-marketing-coupon')
			.where({
				code: code
			})
			.limit(1)
			.get();
		let coupon = {};
		if (couponRes.data && couponRes.data.length === 1) {
			coupon = couponRes.data[0];
		}
		
		if (!(coupon && coupon._id) || coupon.is_delete == 1) {
			response.msg = `兑换码不存在`;
			return response;
		}
		if (coupon.state != '待领取')
		{
			response.msg = `优惠券【${coupon.state}】`;
			return response;
		}
		if (coupon.end_time < Date.now())
		{
			response.msg =`优惠券已过期`;
			return response;
		}
		
		const rule_id = coupon.coupon_id;
		
		// 获取优惠券规则
		const couponRuleRes = await this.db.collection('usemall-marketing-coupon-rule').doc(rule_id).get();
		let couponRule = {};
		if (couponRuleRes.data && couponRuleRes.data.length === 1) {
			couponRule = couponRuleRes.data[0];
		}
		
		if (!(couponRule && couponRule._id) || couponRule.is_delete == 1) {
			response.msg = `优惠券【${rule_id}】不存在`;
			return response;
		}
		if (couponRule.state != '运营中')
		{
			response.msg = `优惠券状态【${couponRule.state}】`;
			return response;
		}
		if (couponRule.end_time < Date.now())
		{
			response.msg =`优惠券已过期`;
			return response;
		}
		
		await this.__receive_coupon(uid, user, rule_id, coupon._id, `【${user.name}】兑换优惠券`);
		
		response.datas = '成功兑换1张优惠券';
		
		const end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}
	
	// 领取优惠券
	async __receive_coupon(uid, user, rule_id, coupon_id, note) {
		// 优惠券数
		await this.db.collection('usemall-member').doc(uid).update({
			member_coupon_cnt: dbcmd.inc(1)
		});
		// 领取数
		await this.db.collection('usemall-marketing-coupon-rule').doc(rule_id).update({
			receive_num: dbcmd.inc(1)
		});
		// 已领取
		await this.db.collection('usemall-marketing-coupon').doc(coupon_id).update({
			version: dbcmd.inc(1),
			state: '已领取',
			
			member_id: uid,
			member_openid: user.openid,
			member_name: user.name,
			member_headimg: user.headimg,
			note: note,
			
			last_modify_time: Date.now(),
			last_modify_uid: uid,
			last_modify_uname: user.name
		});
	}
	
	// 可领券列表
	async receiveList() {
		let response = {
			code: 1,
		};
		const start = new Date().getTime();
		
		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
			}
		}
		if (!uid) {
			response.msg = '当前未登录';
			return response;
		}
		
		const coupons = await this.__get_coupon_rules();
		if (coupons && coupons.length <= 0) {
			response.msg = '系统未发放优惠券';
			return response;
		}
		
		const rule_ids = coupons.map(x => x._id);
		// 根据当前用户，获取已领取优惠券数据
		const member_coupons = await this.__get_member_group_coupons(uid, rule_ids);

		// 返回可领取优惠券规则数据列表
		let datas = [];
		coupons.forEach(x => {
			if (member_coupons.find(m => m._id == x._id && m.num >= x.per_max && x.per_max != 0)) {
				return;
			}
			
			datas.push(x);
		});
		
		response.datas = datas;
		
		const end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}
	
	// 商品可领券列表
	async receiveGoods() {
		let response = {
			code: 1,
		};
		const start = new Date().getTime();
		
		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		
		const {
			goods_id
		} = this.ctx.data;
		
		// 根据当前产品ID，获取产品详情数据
		const goodsRes = await this.db.collection('usemall-goods').doc(goods_id).get();
		if (!(goodsRes.data && goodsRes.data.length === 1)) {
			response.msg = '当前商品无效';
			return response;
		}
		const goods = goodsRes.data[0];
		if (goods.state != '销售中') {
			response.msg= `当前商品-${goods.state}`;
			return response;
		}
				
		const coupons = await this.__get_coupon_rules();
		if (coupons && coupons.length <= 0) {
			response.msg = '系统未发放优惠券';
			return response;
		}
		
		const rule_ids = coupons.map(x => x._id);
		// 根据当前用户，获取已领取优惠券数据
		const member_coupons = await this.__get_member_group_coupons(uid, rule_ids);
		
		// 根据产品ID、分类ID，获取可领取优惠券规则列表
		let datas = [];
		coupons.forEach(x => {
			if (member_coupons.find(m => m._id == x._id && m.num >= x.per_max && x.per_max != 0)) {
				return;
			}
			
			switch (x.allow_type) {
				case 'all':
					datas.push(x);
					break;
				case 'goods':
					if (x.allow_ids.find(m => m == goods_id)) {
						datas.push(x);
					}
					break;
				case 'category':
					if (x.allow_ids.find(m => goods.cids.find(m))) {
						datas.push(x);
					}
					break;
				default:
					break;
			}
		});
		
		response.datas = datas;
		
		const end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}
	
	// 获取可用优惠券
	async __get_coupon_rules() {
		const ruleRes = await this.db.collection('usemall-marketing-coupon-rule')
			.where( 
				dbcmd.and([
					{
						is_delete: 0,
						state: '运营中',
						receive_type: '主动发放',
						member_type: '所有人',
						start_time: $.lte(Date.now()),
						end_time: $.gt(Date.now()) 
					}, 
					dbcmd.expr($.gt(['$num', '$receive_num']))
				])
			)
			.get();
		
		return ruleRes.data;
	}
	
	// 用户已领取优惠券分组数据
	async __get_member_group_coupons(uid, rule_ids) {
		let matchObj = {
			member_id: uid
		};
		if (rule_ids && rule_ids.length > 0) {
			matchObj.coupon_id = dbcmd.in(rule_ids);
		}
		const couponRes = await this.db.collection('usemall-marketing-coupon').aggregate()
			.match(matchObj)
			.group({
				_id: '$coupon_id', 
				num: $.sum(1)
			})
			.end();
		
		return couponRes.data;
	}

	// 订单可用优惠券
	async useOrder() {
		let response = {
			code: 1,
		};
		const start = new Date().getTime();
		
		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		
		const {
			goods_ids
		} = this.ctx.data;
		// 根据当前用户，获取已领取优惠券数据
		const couponRes = await this.db.collection('usemall-marketing-coupon')
			.where({
				is_delete: 0,
				state: '已领取',
				member_id: uid,
				end_time: dbcmd.gte(start)
			})
			.get();
		if (!(couponRes.data && couponRes.data.length > 0)) {
			response.msg = '无可用优惠券';
			return response;
		}
		
		// 根据下单产品ids，获取产品详情数据
		const goodsRes = await this.db.collection('usemall-goods')
			.where({ _id: dbcmd.in(goods_ids), state: '销售中' })
			.field({
				price: true,
				vip_price: true,
				is_vip: true,
				cids: true
			})
			.get();
		if (!(goodsRes.data && goodsRes.data.length > 0)) {
			response.msg = '下单商品无效';
			return response;
		}
		const goodsDatas = goodsRes.data;
		// 下单商品ID集合
		const ids = goodsDatas.map(x => x._id);
		
		let arrs = [];
		goodsDatas.forEach(x => arrs = arrs.concat(x.cids));
		// 下单商品所属分类集合
		const cids = new Set(arrs);
		
		const member_coupons = couponRes.data;
		
		// 根据产品ID、分类ID，获取可领取优惠券规则列表
		let datas = [];
		member_coupons.forEach(x => {
			switch (x.allow_type) {
				case 'all':
					datas.push(x);
					break;
				case 'goods':
					if (x.allow_jsons.find(m => ids.find(g => g == m._id))) {
						datas.push(x);
					}
					break;
				case 'category':
					if (x.allow_ids.find(m => cids.find(c => c == m))) {
						datas.push(x);
					}
					break;
				default:
					break;
			}
		});
		
		response.datas = datas;
		
		const end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}
	
	// 优惠券数据
	async data() {
		let response = {
			code: 1
		};
		
		const start = new Date().getTime();
		const {
			coupon_id
		} = this.ctx.data;
		
		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		
		// 获取优惠券数据
		const couponRes = await this.db.collection('usemall-marketing-coupon').doc(coupon_id).get();
		
		if (couponRes && couponRes.data && couponRes.data.length === 1) 
		{
			response.datas = couponRes.data[0];
		}
		
		const end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}
	
}
